import modal from "@/plugins/modal";
import { getFileNameByUrl } from "@/utils/index";

/**
 * 文件链接下载
 * @param {string} url  -文件链接
 * @param {string} [name]  -文件名
 */
export const aDownFile = (url, name) => {
  if (!url) {
    return modal.msgError("无文件链接");
  }
  try {
    modal.loading("文件请求中...");
    const fileName = name || getFileNameByUrl(url);
    let link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    setTimeout(() => {
      modal.closeLoading();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    }, 1000);
  } catch (err) {
    modal.closeLoading();
    alert(JSON.stringify(err));
  }
};

/**
 * 文档流
 * @param {string} docFlow -文档流
 * @param {string} name -文档名称
 * @param {string} suffix  -后缀名
 */
export const documentFlow = (docFlow, name, suffix) => {
  if (!docFlow) {
    return modal.msgError("文档数据异常");
  }
  if (!name) {
    return modal.msgError("请传入文档名");
  }
  if (!suffix) {
    return modal.msgError("请传入文档后缀名");
  }
  try {
    modal.loading("文件请求中...");
    let url = window.URL.createObjectURL(new Blob([docFlow])),
      fileName = name + "." + suffix,
      link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    setTimeout(() => {
      modal.closeLoading();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    }, 1000);
  } catch (err) {
    modal.closeLoading();
    alert(JSON.stringify(err));
  }
};
